{% extends "base.html" %}

{% block title %}导入Excel - 算法生成照护计划{% endblock %}

{% block page_title %}导入Excel生成照护时间线{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.75);
    }
    
    .result-section {
        margin-top: 20px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.75);
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.3);
        display: none;
    }
    
    .file-upload {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: 2px dashed var(--tech-border);
        border-radius: 8px;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
        transition: all 0.3s;
        background-color: rgba(1, 1, 43, 0.6);
        cursor: pointer;
    }
    
    .file-upload:hover {
        border-color: var(--tech-primary);
        background-color: rgba(1, 1, 43, 0.7);
    }
    
    .file-upload.dragover {
        border-color: var(--tech-accent);
        background-color: rgba(1, 1, 43, 0.8);
    }
    
    .file-upload-icon {
        font-size: 48px;
        color: var(--tech-primary);
        margin-bottom: 10px;
    }
    
    .file-info {
        margin-top: 10px;
        color: #aaa;
    }
    
    .file-name {
        font-weight: bold;
        color: #fff;
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    #loading {
        display: none;
        text-align: center;
        margin: 20px 0;
        color: var(--tech-primary);
    }
    
    .custom-shift-inputs {
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        padding: 15px;
        margin-top: 10px;
        background-color: rgba(1, 1, 43, 0.6);
    }
    
    .shift-input-group {
        margin-bottom: 10px;
        padding-bottom: 10px;
        border-bottom: 1px dashed var(--tech-border);
    }
    
    .shift-input-group:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }
    
    .guide-section {
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 4px;
        background-color: rgba(5, 238, 255, 0.1);
        border: 1px solid var(--tech-border);
    }
    
    .guide-section h6 {
        color: var(--tech-primary);
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }
    
    .guide-section h6 i {
        margin-right: 8px;
    }
    
    .guide-section ul {
        margin-bottom: 0;
        padding-left: 20px;
    }
    
    .guide-section li {
        margin-bottom: 5px;
        color: #ccc;
    }
    
    .error-message {
        color: #ff4d4d;
        font-size: 0.875rem;
        margin-top: 5px;
        display: none;
    }
    
    .invalid-feedback {
        display: none;
        color: #ff4d4d;
        font-size: 0.875rem;
    }
    
    .was-validated .form-control:invalid ~ .invalid-feedback {
        display: block;
    }
    
    .form-control, .form-select {
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        color: #fff;
    }
    
    .form-control:focus, .form-select:focus {
        background-color: rgba(1, 1, 43, 0.9);
        border-color: var(--tech-primary);
        color: #fff;
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.5);
    }
    
    .form-label {
        color: var(--tech-primary);
        font-weight: 500;
    }
    
    .custom-control-label {
        color: #fff;
    }
    
    .text-muted {
        color: #aaa !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="tech-card">
            <div class="tech-card-header">
                <h5 class="card-title"><i class="fas fa-file-excel me-2"></i>导入Excel文件</h5>
            </div>
            <div class="tech-card-body">
                <!-- 操作指引 -->
                <div class="guide-section">
                    <h6><i class="fas fa-info-circle"></i>操作指引</h6>
                    <ul>
                        <li>请先下载Excel模板，按照模板格式填写护理员和老人信息</li>
                        <li>选择排班日期和班制模式（一班制/二班制/三班制）</li>
                        <li>可选择是否自定义班次时间，默认使用系统配置的时间</li>
                        <li>时间间隔可设置为10-60分钟，建议使用20分钟</li>
                        <li>上传完成后系统将自动生成照护时间线</li>
                    </ul>
                </div>
                
                <div class="form-section">
                    <form id="excel-form" enctype="multipart/form-data" novalidate>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="file-upload" id="file-upload-area">
                                    <i class="fas fa-file-excel file-upload-icon"></i>
                                    <h5 class="text-light">点击或拖拽Excel文件到此处</h5>
                                    <p class="text-muted">支持 .xlsx 格式文件</p>
                                    <input type="file" id="excel-file" name="excel_file" accept=".xlsx" style="display: none;" required>
                                    <div class="error-message" id="file-error"></div>
                                    <a href="{{ url_for('views_page.download_excel_template') }}" class="btn tech-btn tech-btn-outline">
                                        <i class="fas fa-download me-2"></i> 下载Excel模板
                                    </a>
                                    <div class="file-info mt-3" id="file-info" style="display: none;">
                                        已选择文件: <span class="file-name" id="file-name"></span>
                                        <button type="button" class="btn btn-sm btn-outline-danger ms-2" id="reset-file">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="schedule_date" class="form-label">排班日期 <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="schedule_date" name="schedule_date" value="{{ current_date }}" required>
                                    <div class="invalid-feedback">请选择排班日期</div>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="shift_mode" class="form-label">班制模式 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="shift_mode" name="shift_mode" required>
                                        <option value="1">一班制 (24小时)</option>
                                        <option value="2">二班制 (每班12小时)</option>
                                        <option value="3" selected>三班制 (每班8小时)</option>
                                    </select>
                                    <div class="invalid-feedback">请选择班制模式</div>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="time_interval_minutes" class="form-label">时间间隔（分钟）<span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="time_interval_minutes" name="time_interval_minutes" 
                                           min="10" max="60" value="20" required>
                                    <div class="invalid-feedback">请输入10-60之间的时间间隔</div>
                                    <small class="form-text text-muted">每个时间段的分钟数（10-60分钟）</small>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="use_custom_shifts" name="use_custom_shifts">
                                        <label class="form-check-label" for="use_custom_shifts">自定义班次时间</label>
                                    </div>
                                </div>
                                
                                <div id="custom-shifts-container" class="custom-shift-inputs" style="display: none;">
                                    <div id="shift-inputs">
                                        <!-- 动态生成的班次输入框将显示在这里 -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center mt-4">
                            <button type="submit" class="btn tech-btn tech-btn-primary" id="submit-btn">
                                <i class="fas fa-upload me-2"></i> 上传并生成排班
                            </button>
                        </div>
                    </form>
                    
                    <div id="loading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">正在处理...</span>
                        </div>
                        <p class="mt-2">正在处理Excel文件并生成排班计划，请稍候...</p>
                    </div>
                </div>
                
                <div class="result-section" id="result-section">
                    <h5 class="text-light mb-3"><i class="fas fa-check-circle text-success me-2"></i> 导入成功</h5>
                    <p id="success-message" class="mb-4 text-light">照护时间线已成功生成!</p>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="tech-inner-card">
                                <div class="p-3">
                                    <h6 class="text-light">批次信息</h6>
                                    <p class="text-light">批次号: <span id="batch-number" class="fw-bold text-light"></span></p>
                                    <p class="text-light">排班日期: <span id="result-date" class="fw-bold text-light"></span></p>
                                    <p class="text-light">生成时间: <span id="create-time" class="fw-bold text-light"></span></p>
                                    <a id="download-link" href="#" class="btn tech-btn tech-btn-success mt-2">
                                        <i class="fas fa-download me-2"></i> 下载排班结果
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 文件上传区域交互
        const fileUploadArea = $('#file-upload-area');
        const fileInput = $('#excel-file');
        const fileInfo = $('#file-info');
        const fileName = $('#file-name');
        const resetFileBtn = $('#reset-file');
        const fileError = $('#file-error');
        
        // 拖拽上传
        fileUploadArea.on('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).addClass('dragover');
        });
        
        fileUploadArea.on('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');
        });
        
        fileUploadArea.on('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');
            
            const files = e.originalEvent.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });
        
        // 点击上传
        fileUploadArea.on('click', function() {
            fileInput.click();
        });
        
        fileInput.on('change', function() {
            if (this.files.length > 0) {
                handleFileSelect(this.files[0]);
            }
        });
        
        // 处理文件选择
        function handleFileSelect(file) {
            if (!file.name.endsWith('.xlsx')) {
                fileError.text('请选择.xlsx格式的Excel文件').show();
                resetFileInput();
                return;
            }
            
            if (file.size > 10 * 1024 * 1024) { // 10MB
                fileError.text('文件大小不能超过10MB').show();
                resetFileInput();
                return;
            }
            
            fileError.hide();
            fileName.text(file.name);
            fileInfo.show();
        }
        
        // 重置文件输入
        function resetFileInput() {
            fileInput.val('');
            fileInfo.hide();
            fileName.text('');
        }
        
        resetFileBtn.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            resetFileInput();
        });
        
        // 更新班次输入
        function updateShiftInputs() {
            const shiftMode = $('#shift_mode').val();
            const container = $('#shift-inputs');
            container.empty();
            
            const shiftNames = {
                1: ['全天班'],
                2: ['白班', '夜班'],
                3: ['早班', '中班', '夜班']
            };
            
            const shifts = shiftNames[shiftMode];
            shifts.forEach((name, index) => {
                container.append(`
                    <div class="shift-input-group">
                        <h6 class="mb-3 text-light">${name}</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label class="form-label">开始时间</label>
                                    <input type="time" class="form-control" name="shift_start_${index}" required>
                                    <div class="invalid-feedback">请输入开始时间</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label class="form-label">结束时间</label>
                                    <input type="time" class="form-control" name="shift_end_${index}" required>
                                    <div class="invalid-feedback">请输入结束时间</div>
                                </div>
                            </div>
                        </div>
                    </div>
                `);
            });
        }
        
        $('#shift_mode').on('change', function() {
            if ($('#use_custom_shifts').prop('checked')) {
                updateShiftInputs();
            }
        });
        
        $('#use_custom_shifts').on('change', function() {
            const container = $('#custom-shifts-container');
            if ($(this).prop('checked')) {
                updateShiftInputs();
                container.slideDown();
            } else {
                container.slideUp();
            }
        });
        
        // 表单验证和提交
        $('#excel-form').on('submit', function(e) {
            e.preventDefault();
            
            const form = $(this);
            if (!form[0].checkValidity()) {
                e.stopPropagation();
                form.addClass('was-validated');
                return;
            }
            
            const formData = new FormData(this);
            
            // 添加自定义班次时间
            if ($('#use_custom_shifts').prop('checked')) {
                const shiftMode = $('#shift_mode').val();
                const customShifts = [];
                
                for (let i = 0; i < shiftMode; i++) {
                    const start = $(`input[name="shift_start_${i}"]`).val();
                    const end = $(`input[name="shift_end_${i}"]`).val();
                    if (!start || !end) {
                        alert('请填写完整的班次时间');
                        return;
                    }
                    customShifts.push({
                        name: String(i + 1),
                        start_time: start,
                        end_time: end
                    });
                }
                
                formData.append('custom_shifts', JSON.stringify(customShifts));
            }
            
            $('#submit-btn').prop('disabled', true);
            $('#loading').show();
            $('#result-section').hide();
            
            $.ajax({
                url: '/import_excel',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#batch-number').text(response.batch_number);
                        $('#result-date').text(response.schedule_date);
                        $('#create-time').text(response.create_time);
                        $('#download-link').attr('href', `/download_schedule_results?batch_number=${response.batch_number}`);
                        $('#result-section').show();
                    } else {
                        alert(response.message || '导入失败，请检查Excel文件格式是否正确');
                    }
                },
                error: function() {
                    alert('服务器错误，请稍后重试');
                },
                complete: function() {
                    $('#submit-btn').prop('disabled', false);
                    $('#loading').hide();
                }
            });
        });
    });
</script>
{% endblock %} 